package com.wxy.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {


    /**
     * 上传单个文件
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file, @RequestParam(required = false) String path) throws IOException {
        // 创建文件夹
        File dest = new File(StrUtil.isNotBlank(path) ? path : "upload");
        if (!dest.exists()) {
            dest.mkdirs();
        }
        // 存储的文件要使用绝对路径，因为transferTo中使用了相对路径
        File file1 = new File(dest.getAbsolutePath() + File.separator + file.getOriginalFilename());
        log.info("上传文件：file = {}", file1.getAbsolutePath());
        file.transferTo(file1);
        return "上传成功：" + file1.getAbsolutePath();
    }

    /**
     * 下载单个文件
     */
    @GetMapping("/download")
    public void download(@RequestParam String filename, HttpServletResponse response) throws IOException {
        File file = new File(filename);
        log.info("下载文件：{}", file.getAbsolutePath());
        //第一步：设置响应类型
        response.setContentType("application/force-download");//应用程序强制下载
        //第二步：设置响应头，对文件进行url编码
        String fileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        FileUtil.writeToStream(file, response.getOutputStream());
    }
}
